package com.hotstrip.web;

import com.hotstrip.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2019/9/6.
 * 上传图片 Controller 类
 */
@RestController
public class UploadImageController {
    private static Logger logger = LoggerFactory.getLogger(UploadImageController.class);

    /**
     * 上传图片接口地址
     * @param multipartHttpServletRequest
     * @return
     */
    @PostMapping(value = "/uploadImage")
    public Object uploadImage(MultipartHttpServletRequest multipartHttpServletRequest){
        // 图片存储路径
        String path = "target/classes/static";
        // 返回值
        HashMap map = new HashMap();
        List<String> data = new ArrayList<>();
        // 取得request中的所有文件名
        Iterator<String> iterator = multipartHttpServletRequest.getFileNames();
        // 遍历
        while (iterator.hasNext()) {
            // 取得上传文件
            MultipartFile multipartFile = multipartHttpServletRequest.getFile(iterator.next());
            if (multipartFile != null) {
                // 文件名
                String fileName = multipartFile.getOriginalFilename();
                // 获取文件拓展名
                String extName = FileUtil.getExtName(fileName);
                if (StringUtils.isEmpty(extName)) {
                    logger.error("文件后缀名称为空，文件可能有问题...");
                    map.put("errno", 1);
                    map.put("data", data);
                    return map;
                }
                // 保证 文件夹存
                File fileDir = new File(path);
                if (!fileDir.exists()){
                    fileDir.mkdirs();
                }
                File file = new File(fileDir, fileName);
                // 拷贝文件流  到上面的文件
                FileUtil.copyInputStreamToFile(multipartFile, file);
                // 新文件名称
                String newFileName = System.currentTimeMillis()+ FileUtil.randomValue(10000)+"."+extName;
                File finalFile = new File(fileDir, newFileName);
                if(file.renameTo(finalFile)){
                    logger.info("上传文件信息接口......重命名文件成功.........【新文件名称：{}】", finalFile.getName());
                }
                // 构建图片的可访问地址
                String webUrl = multipartHttpServletRequest.getScheme()
                        + "://" + multipartHttpServletRequest.getServerName()
                        + ":" + multipartHttpServletRequest.getServerPort()
                        + multipartHttpServletRequest.getContextPath();
                String imageUrl = finalFile.getPath().substring(path.length()).replaceAll("\\\\", "/");
                logger.info("文件路径： {}", webUrl + imageUrl);
                // 添加到数组中
                data.add(webUrl + imageUrl);
            }
        }
        // 返回前端需要的格式
        map.put("errno", 0);
        map.put("data", data);
        return map;
    }
}
